<?php
namespace Home\Controller;
use Think\Controller;
header("Content-type: text/html; charset=utf-8"); 
class ZdController extends CommonController {

  


	//添加图片广告页面
	public function index()
	{
		//每次进入检索所有广告是否有过期的
		check_ad_time();
		$Zd = D('s_zd');
		$Sl = D('slink');
		$user_id = session('uid');
		$file="./App/Common/Conf/config.php"; //全局配置
		$config = include $file;
		$kw = I('kws');
		$sid = I('sid');
		if($user_id<=0){
			$this->error('请先登陆再进行该操作。',U('Login/login'));
		}
		//判断此热词是否是自己的
		$username = M('users')->where(array('userid'=>$user_id))->field('username')->find();
		$scount = D('slink')->where("id=$sid AND author ='$username[username]'")->count();

		if($scount<=0){
			$this->error('您无权操作非自己的链接。',U('Search/index',array('kws'=>$kw)));
		}
		
		$now = time();
		$zd_list = $Zd->where("cat_name='$kw' AND type = 2 AND end_time >= $now")->select();
	
		//查找用户级别
		$vip = $this->cheackvip($user_id);
		if($vip < 1){
			$this->error('只有vip1或者以上的用户才能置顶。');
		}
		

		//读取该热词下所有置顶
		for($i=1;$i<=$config['top_num'];$i++){
			$last_zd_list[$i] = '';
			foreach($zd_list as $k=>$v){
				$zinfo = $Sl->field('img,author,link,title')->where("id=$v[sid]")->find();
				$v['img'] = $zinfo['img'];
				$v['author'] = $zinfo['author'];
				$v['link'] = $zinfo['link'];
				$v['title'] = $zinfo['title'];
				if($v['type']==1){
					$v['last_date'] = '已下架';
				}elseif($v['type']==2){
					$v['last_date'] = $this->get_last_date($v['end_time']);
				}elseif($v['type']==3){
					$v['last_date'] = '已过期';
				}
				if($v['position'] == $i){
					$last_zd_list[$i] = $v;
				}
			}
		}

		$this->assign('last_zd_list',$last_zd_list);  //把值赋给前台模板
		$this->assign('kw',$kw);  //把值赋给前台模板
		$this->assign('sid',$sid);  //把值赋给前台模板
		$this->display();
	}

	public function add()
	{
		$user_id = session('uid');
		$file="./App/Common/Conf/config.php"; //全局配置
		$config = include $file;
		$data = array();
		$paydata = array();
		if($user_id<=0){
			$this->error('请先登陆再进行该操作。',U('Login/login'));
		}
		//查找用户级别
		$vip = $this->cheackvip($user_id);
		if($vip < 1){
			$this->error('只有vip1或者以上的用户才能置顶。');
		}

		if(IS_POST){
			$kw = I('kw');
			$position = I('position');
			$sid = I('sid');
			
			//判断此热词是否是自己的
			$username = M('users')->where(array('userid'=>$user_id))->field('username')->find();
			$scount = D('slink')->where("id=$sid AND author ='$username[username]'")->count();
			if($scount<=0){
				$this->error('您无权操作非自己的链接。',U('Search/index',array('kws'=>$kw)));
			}
			
			if(empty($kw)){
				$this->error('不存在该热词。');
			}
			
			//检查置顶状态
			$adcheck = $this->cheackadd($user_id,$kw,$config['top_num'],$position);
			if($adcheck == 1){
				$this->error('该热词下置顶数量已满'.$config['ad_num'].'个。');
			}elseif($adcheck == 2){
				$this->error('您在该热词下已经置顶过一个。');
			}elseif($adcheck == 3){
				$this->error('不存在该热词。');
			}elseif($adcheck == 5){
			$this->error('请选择正确的置顶位。');
			}elseif($adcheck == 6){
				$this->error('该位置下已有置顶。');
			}
			
			$paydata['buytime']    = I('addday');
			
			if($paydata['buytime']<=0){
				$this->error('请输入置顶天数。');
			}
			
			if($paydata['buytime']>$config['zd_buy_most']){
				$this->error('置顶天数最多为'.$config['zd_buy_most'].'天。');
			}
			
			$data['add_time'] = time();//发布时间
			$data['type'] = 1;//默认状态是下架
			$data['position'] = $position;//置顶位置
			$data['uid'] = $user_id;//用户ID
			$data['sid'] = $sid;//用户ID
			$Cate = D('cate');
			$cat_id = $Cate->where("name='$kw'")->field('id')->select();

			$data['cat_id'] = $cat_id[0]['id'];//热词分类ID
			$data['cat_name'] = $kw;//热词分类名
			$paydata['pay_code'] = I('pay_code');//热词分类名
			
			$price = $config['top_price']*$paydata['buytime'];
			
			if($paydata['pay_code'] == 1){
				//如果是余额支付检查用户余额是否充足
				if(!$this->cheackye($user_id,$price)){
					$this->error('您的余额不足，支付失败。');
				}
			}
			
			$Zd = D('s_zd');
			if($Zd->create($data)){
				//写入购买记录表
				if($Zd->add()){
					$Payaccount = D('pay_account_log');
					$paydata['order_id'] = $Zd->getLastInsID();
					$paydata['uid'] = $user_id;
					$paydata['money'] = $price;
					$paydata['pay_type'] = 1;
					$paydata['type'] = 1;
					$paydata['add_time'] = time();
					$paydata['pay_status'] = 0;
					
					if($paydata['pay_code'] == 1){
						$paydata['pay_status'] = 1;
						$paydata['pay_time'] = time();
					}
					
					$Payaccount->create($paydata);
					$Payaccount->add();
					$payid = $Payaccount->getLastInsID();
					
					if($paydata['pay_code'] == 1){
						$this->account_change($user_id,$price,'用户置顶链接。');
						$this->buy_success($paydata,$data,1);
					}
					
					$this->success('置顶成功',U('Search/index',array('kws'=>$kw)));
				}
			}
		}else{
			$kw = I('kw');
			$position = I('position');
			$sid = I('sid');
			
			//判断此热词是否是自己的
			$username = M('users')->where(array('userid'=>$user_id))->field('username')->find();
			$scount = D('slink')->where("id=$sid AND author ='$username[username]'")->count();
			if($scount<=0){
				$this->error('您无权操作非自己的链接。',U('Search/index',array('kws'=>$kw)));
			}
			
			//检查置顶状态
			$adcheck = $this->cheackadd($user_id,$kw,$config['top_num'],$position);
			if($adcheck == 1){
				$this->error('该热词下置顶数量已满'.$config['top_num'].'个。');
			}elseif($adcheck == 2){
				$this->error('您在该热词下已经置顶过一个。');
			}elseif($adcheck == 3){
				$this->error('不存在该热词。');
			}elseif($adcheck == 5){
			$this->error('请选择正确的置顶位。');
			}elseif($adcheck == 6){
				$this->error('该位置下已有置顶。');
			}
			
			$this->assign('kw',$kw);  //把值赋给前台模板
			$this->assign('sid',$sid);  //把值赋给前台模板
			$this->assign('position',$position);  //把值赋给前台模板
			$this->assign('max_day',$config['zd_buy_most']);  //把值赋给前台模板
			$this->display();
		}

	}
	

	public function edit()
	{
		$user_id = session('uid');
		$file="./App/Common/Conf/config.php"; //全局配置
		$config = include $file;
		$data = array();
		$paydata = array();
		if($user_id<=0){
			$this->error('请先登陆再进行该操作。',U('Login/login'));
		}
		//查找用户级别
		$vip = $this->cheackvip($user_id);
		if($vip < 1){
			$this->error('只有vip1或者以上的用户才能发布广告。');
		}

		//获取参数
		if(IS_POST){
			$zd_id = I('zd_id');
			if($zd_id<=0){
				$this->error('请选择要续费的广告。');
			}
			//检查热词广告状态
			$adcheck = $this->cheackedit($user_id,$config['top_num'],$zd_id);
			if($adcheck == 1){
				$this->error('该热词下置顶数量已满'.$config['top_num'].'个。');
			}elseif($adcheck == 2){
				$this->error('您在该热词下已经置顶过一个。');
			}elseif($adcheck == 3){
				$this->error('不存在该热词。');
			}elseif($adcheck == 5){
			$this->error('请选择正确的置顶位。');
			}elseif($adcheck == 6){
			$this->error('该位置下已有置顶。');
			}elseif($adcheck == 7){
				$this->error('该置顶已下架不能续费。');
			}elseif($adcheck == 8){
				$this->error('该链接不属于您。');
			}elseif($adcheck == 9){
				$this->error('不存在该置顶记录。');
			}elseif($adcheck == 11){
				$this->error('该置顶已经下架，不能续费。');
			}
			$paydata['buytime']    = I('addday');
			$Zd = D('s_zd');
			$zd_info = $Zd->where("zd_id=$zd_id")->find();
			$now = time();
			if($zd_info['end_time'] > $now){
				$last_time = $zd_info['end_time']-$now;
			}else{
				$last_time = 0;
			}
			
			$sum_time = $last_time+($paydata['buytime']*24*3600);
			$day = ceil($sum_time/24/3600); 

			if($day>$config['zd_buy_most']){
				$this->error('置顶天数最多为'.$config['zd_buy_most'].'天。');
			}
			
			$data['add_time'] = time();//发布时间
			$paydata['pay_code'] = I('pay_code');//支付方式
			$price = $config['top_price']*$paydata['buytime'];
			if($paydata['pay_code'] == 1){
				//如果是余额支付检查用户余额是否充足
				if(!$this->cheackye($user_id,$price)){
					$this->error('您的余额不足，支付失败。');
				}
			}
				//更新记录表
				if($Zd->where(array('zd_id'=>$zd_id))->save($data)){
					$Payaccount = D('pay_account_log');
					$paydata['order_id'] = $zd_id;
					$paydata['uid'] = $user_id;
					$paydata['money'] = $price;
					$paydata['pay_type'] = 1;
					$paydata['type'] = 2;
					$paydata['add_time'] = time();
					$paydata['pay_status'] = 0;
					
					if($paydata['pay_code'] == 1){
						$paydata['pay_status'] = 1;
						$paydata['pay_time'] = time();
					}
					
					$Payaccount->create($paydata);
					$Payaccount->add();
					$payid = $Payaccount->getLastInsID();
					
					if($paydata['pay_code'] == 1){
						$this->account_change($user_id,$price,'用户续费置顶。');
						$this->buy_success($paydata,$zd_info,2);
					}
					
					$this->success('续费成功',U('Person/myzd'));
				}else{
					$this->error('续费失败',U('Person/myzd'));
				}
			
		}else{
			$zd_id = I('zd_id');
			$this->assign('zd_id',$zd_id);  //把值赋给前台模板
			$this->assign('max_day',$config['buy_most']);  //把值赋给前台模板
			$this->display();
		}
	}
	
	
	
	//lkl读取剩余时间
	function get_last_date($time){
		$now = time();
		$last_time = $time - $now;

		if($last_time>0){
			$day = floor($last_time/24/3600);
			$hour = floor(($last_time-$day*24*3600)/3600);
		}
		return "剩余{$day}天{$hour}小时";
	}
	
	//判断余额是否充足
	public function cheackye($user_id,$money){
		$users =D('users');
		//查找用户级别
		$usercmoney = $users->field('cmoney')->where(array('userid'=>$user_id))->select();
		if($usercmoney[0]['cmoney'] >= $money){
			return true;
		}else{
			return false;
		}
	}
	
	//检查vip是否足够
	public function cheackvip($user_id){
		$users =D('users');
		//查找用户级别
		if($user_id>0){
			$usersvip = $users->field('vip')->where(array('userid'=>$user_id))->find();
			return $usersvip['vip'];
		}
		return 0;
	}
	
	//判断该用户在此热词下是否已经置顶过
	public function cheackadd($user_id,$kw,$num,$position){
		$Zd = D('s_zd');
		$Cate = D('cate');
		$time = time();

		if(!empty($kw)){
			$zdcount = $Zd->join('cate ON cate.id = s_zd.cat_id')->where("cate.name='$kw' AND s_zd.type=2 AND s_zd.end_time > $time ")->count();
			if($adcount>=$num){
				return 1;//热词下的置顶超过上限
			}
			
			$adcountuser = $Zd->join('cate ON cate.id = s_zd.cat_id')->where("cate.name='$kw' AND s_zd.uid = $user_id AND s_zd.type = 2 AND s_zd.end_time > $time")->count();
			
			if($adcountuser>=1){
				return 2;//用户只能在这个热词下发布一个置顶
			}
			$catecount = $Cate->where("name='$kw'")->count();
			if($catecount<=0){
				return 3;//不存在的热词
			}
			if(empty($position)){
				return 5;//不存在这个置顶位
			}else{
				$positioncount = $Zd->where("cat_name='$kw' AND s_zd.type=2 AND position = $position ")->count();
				if($positioncount>0){
					return 6;//广告位已经有置顶存在
				}
			}
			return 4;
		}
		return 3;
	}
	
	//处理购买成功后余额变动和广告状态时间变动
	public function buy_success($paydata,$data,$type){
		$Zd = D('s_zd');
		$zd_info = $Zd->where("zd_id=$paydata[order_id]")->find();
		$now = time();
		if($type == 1){
			$end_time = $now+$paydata['buytime']*24*3600;
		}else{
			if($zd_info['end_time'] >$now){
				$end_time = $zd_info['end_time'] +$paydata['buytime']*24*3600;
			}else{
				$end_time = $now+$paydata['buytime']*24*3600;
			}
		}
		$Zd->where(array('zd_id'=>$paydata['order_id']))->save(array('end_time'=>$end_time,'type'=>2));
		//设置sid的sort属性
		$sort = 100-$data['position'];
		D('slink')->where(array('id'=>$data['sid']))->save(array('sort'=>$sort,'zd_end_time'=>$end_time));
		return true;
	}
	
	//处理购买成功后余额变动和广告状态时间变动
	public function account_change($user_id,$money,$desc){
		//扣除用户余额
		$userinfo=D('users');
		$where = array('userid'=>$user_id);
		$fields = array('cmoney');
		$userinfos = $userinfo->field($fields)->where($where)->find();

		/*扣除余额*/
		$new_money = $userinfos['cmoney'] - $money;

		M('users')->where(array('userid'=>$user_id))->save(array('cmoney'=>$new_money));
		/*写入日志*/
		$data = array(
			'user_id'=>$user_id,
			'money'=>(-1)*$money,
			'add_time'=>time(),
			'desc'=>$desc
			);
		M('user_account_log')->add($data);
		return true;
	}
	
	//判断该用户在此热词下是否已经发布过图片
	public function cheackedit($user_id,$num,$zd_id){
		$Zd = D('s_zd');
		$Cate = D('cate');
		$now = time();
		//查询该广告是否过期
		$zd_info = $Zd->where("zd_id=$zd_id")->find();

		if(!empty($zd_info)){
			if($zd_info['uid']!=$user_id){
				return 8;//广告不属于此用户
			}
			if($zd_info['type'] == 1){
				return 11;
			}
			if($zd_info['end_time']>$now){
				//如果是未过期续费，直接放行
				if($zd_info['type']>1){
					return 10;
				}else{
					return 7;//下架不能续费
				}
			}else{
				//如果是过期续费，要验证重新发布
				return $this->cheackadd($user_id,$zd_info['cat_name'],$num,$zd_info['position']);
			}
		}else{
			return 9;
		}
		
	}
}
 